import Vue from 'vue'
import VueRouter from 'vue-router'

import Login from '../components/login.vue'
import Home from '../components/Home.vue'
import Welcome from '../components/Welcome.vue'
import Users from '../components/user/User.vue'
import Roles from '../components/power/Roles.vue'
import Rights from '../components/power/Rights.vue'
import Cate from '../components/goods/Cate.vue'
import Params from '../components/goods/Params.vue'
import ShopList from '../components/goods/ShopList.vue'
import AddPage from '../components/goods/Add.vue'
import Order from '../components/order/Order.vue'
import Report from '../components/report/Report.vue'

Vue.use(VueRouter)

//使用element ui菜单导航路由报错解决方法
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err)
}

// const routes = [
//   {
//     path: '/',
//     name: 'home',
//     component: Home
//   },
//   {
//     path: '/about',
//     name: 'about',
//     component: () => import(/* webpackChunkName: "about" */ '../views/About.vue')
//   }
//     // route level code-splitting
//     // this generates a separate chunk (about.[hash].js) for this route
//     // which is lazy-loaded when the route is visited.  
// ]

const routes = [
  {path: '/', redirect: '/login'},
  {
    path: '/login',
    name: 'login',
    component: Login
  },
  {
    path: '/home',
    name: 'home',
    component: Home,
    children: [{
      path: '/home', redirect: '/welcome'
    },{
      path: '/welcome', component: Welcome
    },{
      path: '/users', component: Users
    },{
      path: '/roles', component: Roles
    },{
      path: '/rights', component: Rights
    },{
      path: '/categories', component: Cate
    },{
      path: '/params' , component: Params
    },{
      path: '/goods' , component: ShopList
    },{
      path: '/goods/add', component: AddPage
    },{
      path: '/orders', component: Order
    },{
      path: '/reports', component: Report
    }

  ]
  }
]

const router = new VueRouter({
  routes
})

//挂载路由导航守卫
router.beforeEach((to, from, next) => {
  //to代表将要访问的路径
  //from从哪个页面出发
  //next是一个函数，表示放行
  if (to.path === '/login') return next();
  //获取本地的token
  const tokenStr = window.sessionStorage.getItem('token');
  if (!tokenStr) return next('/login')
  next()
})

export default router
